// pages/chart-preview/chart-preview.js
const storageManager = require('../../utils/storage.js');

Page({
    /**
     * 页面的初始数据
     */
    data: {
        chartId: '',
        chartData: null,
        chartTitle: '',
        chartSubtitle: '',
        
        // 图表配置
        ec: {
            lazyLoad: true
        },
        chart: null,
        
        // 全屏模式
        isFullscreen: false,
        
        // 保存图片状态
        isSaving: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log('chart-preview onLoad:', options);
        
        const chartId = options.id;
        if (!chartId) {
            wx.showToast({
                title: '图表ID不存在',
                icon: 'error'
            });
            setTimeout(() => {
                wx.navigateBack();
            }, 1500);
            return;
        }
        
        this.setData({
            chartId: chartId
        });
        
        this.loadChartData(chartId);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        // 初始化图表
        this.initChart();
    },

    /**
     * 加载图表数据
     */
    loadChartData(chartId) {
        const chartData = storageManager.getChartData(chartId);
        console.log('Loading chart data for preview:', chartData);
        
        if (!chartData) {
            wx.showToast({
                title: '图表数据不存在',
                icon: 'error'
            });
            setTimeout(() => {
                wx.navigateBack();
            }, 1500);
            return;
        }
        
        this.setData({
            chartData: chartData,
            chartTitle: chartData.title || '未命名图表',
            chartSubtitle: chartData.subtitle || ''
        });
    },

    /**
     * 初始化图表
     */
    initChart() {
        this.ecComponent = this.selectComponent('#previewChart');
        
        this.setData({
            ec: {
                onInit: this.initChartInstance.bind(this)
            }
        });
    },

    /**
     * 初始化图表实例
     */
    initChartInstance(canvas, width, height, dpr) {
        const echarts = require('../../components/ec-canvas/echarts');
        
        const chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr
        });
        
        // 使用已保存的图表配置或根据数据重新生成
        let option = this.data.chartData.chartOption;
        if (!option && this.data.chartData.tableData) {
            option = this.createChartOption();
        }
        
        if (option) {
            chart.setOption(option);
        }
        
        this.setData({
            chart: chart
        });
        
        return chart;
    },

    /**
     * 创建图表配置（备用方案）
     */
    createChartOption() {
        const { chartData } = this.data;
        if (!chartData || !chartData.tableData) return null;
        
        const { tableData } = chartData;
        
        // 提取数据
        const categories = tableData.rows.map(row => row[0]);
        const values = tableData.rows.map(row => row[1]);
        
        return {
            backgroundColor: 'transparent',
            title: {
                text: this.data.chartTitle,
                subtext: this.data.chartSubtitle,
                left: 'center',
                textStyle: {
                    color: '#00f5ff',
                    fontSize: 20,
                    fontWeight: 'bold'
                },
                subtextStyle: {
                    color: '#888',
                    fontSize: 14
                }
            },
            tooltip: {
                trigger: 'axis',
                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                borderColor: '#00f5ff',
                borderWidth: 1,
                textStyle: {
                    color: '#fff'
                }
            },
            legend: {
                data: [tableData.headers[1]],
                top: '10%',
                textStyle: {
                    color: '#fff'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                top: '25%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: categories,
                axisLine: {
                    lineStyle: {
                        color: '#00f5ff'
                    }
                },
                axisLabel: {
                    color: '#fff'
                },
                axisTick: {
                    lineStyle: {
                        color: '#00f5ff'
                    }
                }
            },
            yAxis: {
                type: 'value',
                axisLine: {
                    lineStyle: {
                        color: '#00f5ff'
                    }
                },
                axisLabel: {
                    color: '#fff'
                },
                axisTick: {
                    lineStyle: {
                        color: '#00f5ff'
                    }
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(0, 245, 255, 0.2)'
                    }
                }
            },
            series: [{
                name: tableData.headers[1],
                type: 'line',
                data: values,
                smooth: true,
                lineStyle: {
                    color: '#00f5ff',
                    width: 3,
                    shadowColor: 'rgba(0, 245, 255, 0.5)',
                    shadowBlur: 10
                },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [{
                            offset: 0,
                            color: 'rgba(0, 245, 255, 0.3)'
                        }, {
                            offset: 1,
                            color: 'rgba(0, 245, 255, 0.05)'
                        }]
                    }
                },
                itemStyle: {
                    color: '#00f5ff',
                    borderColor: '#fff',
                    borderWidth: 2,
                    shadowColor: 'rgba(0, 245, 255, 0.8)',
                    shadowBlur: 5
                },
                emphasis: {
                    itemStyle: {
                        color: '#ff0096',
                        borderColor: '#fff',
                        borderWidth: 3,
                        shadowColor: 'rgba(255, 0, 150, 0.8)',
                        shadowBlur: 10
                    }
                }
            }]
        };
    },

    /**
     * 切换全屏模式
     */
    toggleFullscreen() {
        this.setData({
            isFullscreen: !this.data.isFullscreen
        });
        
        // 延迟更新图表尺寸
        setTimeout(() => {
            if (this.data.chart) {
                this.data.chart.resize();
            }
        }, 300);
    },

    /**
     * 保存图片到相册
     */
    saveToAlbum() {
        if (this.data.isSaving) return;
        
        this.setData({
            isSaving: true
        });
        
        wx.showLoading({
            title: '正在保存...'
        });
        
        // 使用ec-canvas的canvasToTempFilePath方法
        this.ecComponent.canvasToTempFilePath({
            success: (res) => {
                console.log('Canvas to temp file success:', res);
                
                // 保存到相册
                wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: () => {
                        wx.hideLoading();
                        wx.showToast({
                            title: '保存成功',
                            icon: 'success'
                        });
                    },
                    fail: (error) => {
                        console.error('Save to album failed:', error);
                        wx.hideLoading();
                        
                        if (error.errMsg.includes('auth deny')) {
                            wx.showModal({
                                title: '授权提示',
                                content: '需要您授权保存图片到相册',
                                confirmText: '去授权',
                                success: (res) => {
                                    if (res.confirm) {
                                        wx.openSetting();
                                    }
                                }
                            });
                        } else {
                            wx.showToast({
                                title: '保存失败',
                                icon: 'error'
                            });
                        }
                    },
                    complete: () => {
                        this.setData({
                            isSaving: false
                        });
                    }
                });
            },
            fail: (error) => {
                console.error('Canvas to temp file failed:', error);
                wx.hideLoading();
                wx.showToast({
                    title: '生成图片失败',
                    icon: 'error'
                });
                this.setData({
                    isSaving: false
                });
            }
        });
    },

    /**
     * 编辑图表
     */
    editChart() {
        wx.navigateTo({
            url: `/pages/addCharts/addCharts?id=${this.data.chartId}`
        });
    },

    /**
     * 分享图表
     */
    shareChart() {
        wx.showActionSheet({
            itemList: ['分享给朋友', '生成分享图片'],
            success: (res) => {
                if (res.tapIndex === 0) {
                    // 使用小程序原生分享
                    this.onShareAppMessage();
                } else if (res.tapIndex === 1) {
                    // 生成分享图片
                    this.saveToAlbum();
                }
            }
        });
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        return {
            title: `查看我的图表：${this.data.chartTitle}`,
            path: `/pages/chart-preview/chart-preview?id=${this.data.chartId}`,
            imageUrl: '' // 可以添加自定义分享图片
        };
    }
});
